<template>
  <div>
    <!-- 头部 -->
    <van-nav-bar
      title="搜索结果"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 内容 -->
    <div class="count">
      <!--
        下拉刷新组件
        immediate-check 是否在初始化时立即执行滚动位置检查
      -->
      <van-list
        v-model="loading"
        :immediate-check="false"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- 文章列表组件 -->
        <article-item
          v-for="item in articlesList"
          :key="item.art_id"
          :articles-list="item"
          @click.native="getDetail(item.art_id)"
        />
      </van-list>
    </div>
  </div>
</template>

<script>
// 引入接口
import { searchApi } from '@/api'
// 引入组件
import ArticleItem from '@/views/Home/components/home-list-item.vue'
export default {
  name: 'search-result',
  data () {
    return {
      // 文章列表
      articlesList: [],
      // 调接口需要穿的参数
      searchObj: {
        page: '1',
        per_page: '10',
        q: ''
      },
      // 控制加载状态
      finished: false,
      loading: false
    }
  },
  components: {
    ArticleItem
  },
  mounted () {
    this.getSearchList()
  },
  activated () {
    this.getSearchList()
  },
  methods: {
    async getSearchList () {
      this.searchObj.page = 1
      this.searchObj.q = this.$route.query.option
      const { data } = await searchApi(this.searchObj)
      // console.log(data)
      // 给组件传入数据
      this.articlesList = data.results
    },
    // 点击详情
    getDetail (artId) {
      this.$router.push({
        path: '/detail',
        query: {
          id: artId
        }
      })
    },
    // 上拉加载下一页
    async onLoad () {
      this.searchObj.page++
      // 页面触底 触发onload事件  请求数据
      const { data } = await searchApi(this.searchObj)
      // 把请求回来的数据和已有数据进行拼接
      this.articlesList = [...this.articlesList, ...data.results]
      // 数据加载完毕将 loading 设置为true 停止动画
      this.loading = false
      // 自行判断 全部数据加载完毕 finished设置为true
      if (data.results.length === 0) {
        this.finished = true
      }
    }
  }

}
</script>

<style lang="less">
.van-nav-bar__content {
  position: fixed;
  background-color: #007bff;
  .van-nav-bar__title {
    color: #fff;
  }
  .van-icon {
    color: #fff !important;
  }
}
.count {
  position: fixed;
  top:44px;
  bottom:0px;
  width: 100%;
  overflow: auto;
}
</style>
